Hey all!
I have been tackling a problem that I have in my assignment for the better part of ten hours now and I am at an utter loss.
My problem is that I do not understand how to go about copying the information from two separate char arrays into a a char[20] inside a struct without using strcpy.
First, I will explain the context.
In the given main program,
I have the following enums:
Code:
enum card_suits { Diamonds, Hearts, Clubs, Spades, Suits };
enum card_values { Ace, Two, Three, Four, Five, Six,
Seven, Eight, Nine, Ten, Jack, Queen,
King, Values };
and the following representations of them:
Code:
static char *suits[Suits] = { "Diamonds", "Hearts", "Clubs", "Spades" };
static char *values[Values] = { "ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king" };
In addition, I have the following struct to work with:
Code:
typedef struct Cardstruct {
enum Card_suits suit;
enum Card_values value;
char cardname[20];
} *Card;
Don't ask me why the struct uses *Card instead of Card, I would like to know that as well, but this is how the main program is given. The cardname should hold a string that is a fusion of the presentations of suit and value of a given card. For example, for two of hearts, the cardname should be "Hearts2".
My assignment was to write a function which takes a card suit and value, and then creates a new card.
Based on this, I have written the following function:
Code:
Card newcard(int suit, int value)
{
card newCard = malloc(sizeof(*newCard));
if ((suit<=3)&&(value<=12)){
newCard->suit = suit;
newCard->value = value;
char *buffer = malloc(sizeof suits[suit]+1);
char *buffer2 = malloc(sizeof values[value]+1);
char *pointer = malloc(20*sizeof(char));
pointer = (*newCard).cardname;
int i = 0;
while(*buffer){
pointer[i++]=*buffer++;
}
while(*buffer2){
pointer[i++]=*buffer2++;
}
pointer[i]='\0';
free(*buffer);
buffer = NULL;
free(*buffer2);
buffer2 = NULL;
return newCard;
}
else
return NULL;
}
However, I am unable to understand how I should go about copying the representations of a card from the static chars into the cardname[20] field of each card. The libraries that are allowed to be used in the assignment are stdlib.h and stdio.h, and therefore I am not allowed to use strcpy.
Please help me fix my function . For each hint that points me in the right direction, I promise a cookie to that hint's giver